//! 负载均衡配置管理

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::time::Duration;

/// 负载均衡配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoadBalancerConfig {
    /// 负载均衡算法类型
    pub algorithm: LoadBalancingAlgorithm,
    /// 后端服务器配置
    pub backends: Vec<BackendConfig>,
    /// 健康检查配置
    pub health_check: HealthCheckConfig,
    /// 会话保持配置
    pub session_persistence: SessionPersistenceConfig,
    /// 超时配置
    pub timeout: TimeoutConfig,
    /// 重试配置
    pub retry: RetryConfig,
    /// 连接池配置
    pub connection_pool: ConnectionPoolConfig,
}

/// 负载均衡算法类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LoadBalancingAlgorithm {
    /// 轮询
    RoundRobin,
    /// 加权轮询
    WeightedRoundRobin,
    /// 最少连接
    LeastConnections,
    /// 加权最少连接
    WeightedLeastConnections,
    /// IP哈希
    IpHash,
    /// 一致性哈希
    ConsistentHash,
    /// 随机
    Random,
    /// 加权随机
    WeightedRandom,
    /// 最短响应时间
    LeastResponseTime,
    /// 资源感知
    ResourceAware,
}

/// 后端服务器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendConfig {
    /// 服务器ID
    pub id: String,
    /// 服务器地址
    pub address: SocketAddr,
    /// 权重（1-100）
    pub weight: u32,
    /// 最大连接数
    pub max_connections: u32,
    /// 服务器标签
    pub labels: HashMap<String, String>,
    /// 是否启用
    pub enabled: bool,
    /// 健康检查间隔
    pub health_check_interval_secs: u64,
    /// 区域/可用区信息
    pub zone: Option<String>,
    /// 资源容量
    pub capacity: ResourceCapacity,
}

/// 资源容量配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceCapacity {
    /// CPU核心数
    pub cpu_cores: u32,
    /// 内存大小（MB）
    pub memory_mb: u64,
    /// 最大并发沙箱数
    pub max_sandboxes: u32,
    /// 网络带宽（Mbps）
    pub network_bandwidth_mbps: u32,
}

/// 健康检查配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckConfig {
    /// 启用健康检查
    pub enabled: bool,
    /// 检查间隔
    pub interval: Duration,
    /// 超时时间
    pub timeout: Duration,
    /// 健康阈值（连续成功次数）
    pub healthy_threshold: u32,
    /// 不健康阈值（连续失败次数）
    pub unhealthy_threshold: u32,
    /// 健康检查路径
    pub path: String,
    /// 预期状态码
    pub expected_codes: Vec<u16>,
    /// 检查方法
    pub method: HealthCheckMethod,
}

/// 健康检查方法
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HealthCheckMethod {
    /// HTTP GET请求
    Http,
    /// TCP连接检查
    Tcp,
    /// gRPC健康检查
    Grpc,
    /// 自定义命令
    Command(String),
}

/// 会话保持配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionPersistenceConfig {
    /// 启用会话保持
    pub enabled: bool,
    /// 会话保持方式
    pub method: SessionPersistenceMethod,
    /// 会话超时时间
    pub timeout: Duration,
    /// Cookie名称（仅Cookie方式）
    pub cookie_name: Option<String>,
    /// 哈希键（仅Hash方式）
    pub hash_key: Option<String>,
}

/// 会话保持方式
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SessionPersistenceMethod {
    /// 基于Cookie
    Cookie,
    /// 基于IP哈希
    IpHash,
    /// 基于自定义哈希键
    CustomHash,
    /// 基于JWT Token
    JwtToken,
}

/// 超时配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeoutConfig {
    /// 连接超时
    pub connect_timeout: Duration,
    /// 请求超时
    pub request_timeout: Duration,
    /// 空闲超时
    pub idle_timeout: Duration,
    /// 保活超时
    pub keepalive_timeout: Duration,
}

/// 重试配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    /// 启用重试
    pub enabled: bool,
    /// 最大重试次数
    pub max_retries: u32,
    /// 重试间隔
    pub retry_interval: Duration,
    /// 可重试的状态码
    pub retryable_status_codes: Vec<u16>,
    /// 退避策略
    pub backoff_strategy: BackoffStrategy,
}

/// 退避策略
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BackoffStrategy {
    /// 固定间隔
    Fixed,
    /// 线性退避
    Linear,
    /// 指数退避
    Exponential,
    /// 随机抖动
    RandomJitter,
}

/// 连接池配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionPoolConfig {
    /// 初始连接数
    pub initial_size: u32,
    /// 最大连接数
    pub max_size: u32,
    /// 最小空闲连接数
    pub min_idle: u32,
    /// 连接获取超时
    pub acquire_timeout: Duration,
    /// 连接空闲超时
    pub idle_timeout: Duration,
    /// 连接最大生命周期
    pub max_lifetime: Duration,
}

impl Default for LoadBalancerConfig {
    fn default() -> Self {
        Self {
            algorithm: LoadBalancingAlgorithm::RoundRobin,
            backends: vec![],
            health_check: HealthCheckConfig::default(),
            session_persistence: SessionPersistenceConfig::default(),
            timeout: TimeoutConfig::default(),
            retry: RetryConfig::default(),
            connection_pool: ConnectionPoolConfig::default(),
        }
    }
}

impl Default for BackendConfig {
    fn default() -> Self {
        Self {
            id: "default".to_string(),
            address: "127.0.0.1:8080".parse().unwrap(),
            weight: 100,
            max_connections: 1000,
            labels: HashMap::new(),
            enabled: true,
            health_check_interval_secs: 30,
            zone: None,
            capacity: ResourceCapacity::default(),
        }
    }
}

impl Default for ResourceCapacity {
    fn default() -> Self {
        Self {
            cpu_cores: 4,
            memory_mb: 8192,
            max_sandboxes: 100,
            network_bandwidth_mbps: 1000,
        }
    }
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            interval: Duration::from_secs(30),
            timeout: Duration::from_secs(5),
            healthy_threshold: 3,
            unhealthy_threshold: 3,
            path: "/health".to_string(),
            expected_codes: vec![200],
            method: HealthCheckMethod::Http,
        }
    }
}

impl Default for SessionPersistenceConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            method: SessionPersistenceMethod::IpHash,
            timeout: Duration::from_secs(3600), // 1小时
            cookie_name: Some("LB_SESSION".to_string()),
            hash_key: None,
        }
    }
}

impl Default for TimeoutConfig {
    fn default() -> Self {
        Self {
            connect_timeout: Duration::from_secs(5),
            request_timeout: Duration::from_secs(30),
            idle_timeout: Duration::from_secs(300), // 5分钟
            keepalive_timeout: Duration::from_secs(60),
        }
    }
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_retries: 3,
            retry_interval: Duration::from_millis(500),
            retryable_status_codes: vec![500, 502, 503, 504],
            backoff_strategy: BackoffStrategy::Exponential,
        }
    }
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            initial_size: 10,
            max_size: 100,
            min_idle: 5,
            acquire_timeout: Duration::from_secs(10),
            idle_timeout: Duration::from_secs(600), // 10分钟
            max_lifetime: Duration::from_secs(3600), // 1小时
        }
    }
}